import pandas as pd

# 1）获取数据

titanic = pd.read_csv("data/titanic.csv")
# print(titanic)
# 筛选特征值和目标值
x = titanic[['pclass', 'age', 'sex']]
y = titanic['survived']
# print(x.info())# 对当前选择的特征进行探查
# print(x.head())
# print(y.head())
# 2）数据处理
# ​		缺失值处理
x['age'].fillna(x['age'].mean(), inplace=True)
# print(x.info())
# print(x['age'])
# ​		类别转换成字典
x = x.to_dict(orient="records")
# print(x)
# ​		准备好特征值，目标值
#
# ​		数据划分
from sklearn.model_selection import train_test_split, GridSearchCV

x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=22)
# 3）特征工程
#
# ​		字典特征抽取
from sklearn.feature_extraction import DictVectorizer

transfer = DictVectorizer()
x_train = transfer.fit_transform(x_train)
x_test = transfer.transform(x_test)
# 4）决策树预估器流程
from sklearn.tree import DecisionTreeClassifier, export_graphviz

estimator = DecisionTreeClassifier(criterion="entropy",max_depth=8)
# 加入网格搜索与交叉验证
# 参数准备
# param_dict = {"n_neighbors": [1, 3, 5, 7, 9, 11]}
# estimator = GridSearchCV(estimator, param_grid=param_dict)

estimator.fit(x_train, y_train)
# 5）模型评估
# 方法一：直接比对真实值和预测值
y_predict = estimator.predict(x_test)
print("y_predict:\n", y_predict)
print("直接比对真实值和预测值：\n", y_test == y_predict)

# 方法二:计算准确率
score = estimator.score(x_test, y_test)
print("准确率为:\n", score)

# # 最佳参数：best_params_
# print("最佳参数：\n", estimator.best_params_)
# # 最佳结果：best_score_
# print("最佳结果：\n", estimator.best_score_)
# # 最佳估计器：best_estimator_
# print("最佳估计器:\n", estimator.best_estimator_)
# # 交叉验证结果：cv_results_
# print("交叉验证结果:\n", estimator.cv_results_)

# 可视化决策树
export_graphviz(estimator, out_file="data/titanic_tree.dot", feature_names=transfer.get_feature_names())
